class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        if (postorder == null) {
            throw new RuntimeException("invalid parameters");
        }
        return recur(postorder, 0, postorder.length - 1);
    }

    public boolean recur(int[] arr, int left, int right) {
        if (left >= right) return true;
        int i = left;
        while (arr[right] > arr[i]) i++;
        int j = i;
        while (arr[i] > arr[right]) i++;
        return i == right && recur(arr, left, j - 1) && recur(arr, j, i - 1);
    }
}

